package simpleeditor.controllers;

import simpleeditor.Constants;
import simpleeditor.Ui_SimpleEditor;
import simpleeditor.model.Group;
import simpleeditor.model.GroupManager;

import com.trolltech.qt.gui.QTableWidgetItem;

public class GroupController extends TableEditController {

	private static final int GROUP_NAME_COLUMN=0;
	private static final int MULTIPLICITY_COLUMN=1;
	
	private String selectedGroup;
	
	private GroupManager gm;
	private PropertyController pc;
	
	public GroupController(Ui_SimpleEditor ui, GroupManager gm, PropertyController pc) {
		super(ui.groupsTableWidget,ui.addGroupButton,ui.removeGroupButton);
		this.gm=gm;
		this.pc=pc;
		
		pc.init(this);
		ui.groupsTableWidget.itemSelectionChanged.connect(this,"enableProperties()");
		
	}

	@Override
	public void addRow() {
		String groupId;
		
		groupId=gm.newGroup();
		
		table.setRowCount(table.rowCount()+1);
		table.setItem(table.rowCount()-1, GROUP_NAME_COLUMN, new QTableWidgetItem(groupId));
		table.setItem(table.rowCount()-1, MULTIPLICITY_COLUMN, new QTableWidgetItem(""+gm.getGroup(groupId).getMultiplicity()));

	}
	
	public void enableProperties(){
			boolean selected;
			String g;
			boolean different;
			
			
			selected=table.selectedItems().size()!=0;
			pc.enableAddProperty(selected);
			
			if(selected){
				g=table.item(table.selectedItems().get(0).row(),GROUP_NAME_COLUMN).text();
			}else{
				g=null;
			}
			
			different=((g==null)&&(selectedGroup!=null))
					  ||(!(g.equals(selectedGroup)));
			
			selectedGroup=g;
			
			if(selectedGroup==null){
				pc.clear();
			}else if(different){
				pc.showProperties(gm.getGroup(selectedGroup).getProperties());
			}
			
	}

	protected Group getSelectedGroup() {
		return gm.getGroup(selectedGroup);
	}

	@Override
	protected void removeFromModel(String group) {
		pc.clear();
		gm.removeGroup(group);
	}
	
	public void editItem(){

		QTableWidgetItem selected;
		int column;
	
		selected=table.selectedItems().get(0);
		column=selected.column();
		
		if(column==MULTIPLICITY_COLUMN){
			editInteger(MULTIPLICITY_COLUMN, 0, Constants.MAX_MULTIPLICITY);
		}else{
			editText(GROUP_NAME_COLUMN);
		}
	}

	@Override
	protected boolean updateModel(int row, int column,int oldValue, int newValue) {
		gm.getGroup(table.item(row, GROUP_NAME_COLUMN).text()).setMultiplicity(newValue);
		return true;
	}

	@Override
	protected boolean updateModel(int row, int column,String oldValue, String newValue) {
		String newName,oldName;
		Group g;
		
		oldName=oldValue;
		newName=newValue;
		
		if(gm.getGroup(newName)==null){
			//TODO: fixa i mappaggi
			g=gm.removeGroup(oldName);
			g.setName(newName);
			gm.addGroup(g);
		
			return true;
		}else{
			return false;
		}
	}

	@Override
	protected boolean updateModel(int row, int editedColumn2, int currentIndex,
			String text, String currentText) {
		return true;
	}
	
}
